# coding=utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
import json
import traceback
from django.shortcuts import render

from apps.borrow.models import BorrowRecord
from apps.common.requests import err_requests
from apps.archive_cabinets.models import Lattice
from apps.common.requests import success_requests

from apps.common.requests import get_body
from models import ArchivesFile, CloudAuthUser, Cabinet, Box


def files_json(request):
    if request.method.upper() == "POST":
        request_params = get_body(request)
        try:
            cabinet_id = request_params.get("cabinet_id")
            lattice_id = request_params.get("lattice_id")
            box_id = request_params.get("box_id")
            file_status = request_params.get("file_status")
            title = request_params.get("title")
            records = ArchivesFile.objects

            print "cabinet_id: %s " % cabinet_id
            print "lattice_id: %s " % lattice_id
            print "box_id: %s " % box_id

            if cabinet_id or lattice_id or box_id:  # 三级查询
                if cabinet_id:
                    records = records.filter(cabinet=int(cabinet_id))
                if lattice_id:
                    records = records.filter(lattice=int(lattice_id))
                if box_id:
                    records = records.filter(box=int(box_id))
            else:  # 查询全部
                records = records.filter()
            if file_status and str(file_status) != '全部':  # 状态查询
                records = records.filter(file_status=file_status)
            if title:  # 模糊查询
                records = records.filter(title__contains=title)
            records = records.order_by("-storage_time")
            extend = dict()
            for each in records:
                one = dict()
                one['location'] = each.location
                one['operator_username'] = each.operator_username
                one['owner_username'] = each.owner_username
                one['department_name'] = each.department_name
                extend[each.id] = one
            result = list(records.values())
            for each in result:  # 前端需要
                each['location'] = extend.get(each['id'])['location']
                each['operator_username'] = extend.get(each['id'])['operator_username']
                each['owner_username'] = extend.get(each['id'])['owner_username']
                each['department_name'] = extend.get(each['id'])['department_name']
        except Exception as e:
            print traceback.format_exc()
            return err_requests("500")
        return success_requests(result)
    else:
        return err_requests("500")


def files(request):
    result = {"code": 1, "message": "success", "success": 1}
    if request.method.upper() == "GET":
        try:
            records = ArchivesFile.objects.filter()
            cabinets = Cabinet.objects.all().order_by("id")
            tree_data = list()
            for each in cabinets:
                cabinet = {"text": each.code, "id": each.id}
                # 根据柜子id 获取对应的格子
                c = Cabinet(id=int(cabinet.get("id")))
                lattices = Lattice.objects.filter(cabinet=c).order_by("id")
                if lattices and len(lattices) > 0:
                    cabinet["children"] = list()
                    for one in lattices:
                        lattice = {"text": one.code, "id": one.id}
                        la = Lattice(id=int(lattice.get("id")))
                        boxs = Box.objects.filter(lattice=la).order_by("id")
                        lattice["children"] = list()
                        if boxs and len(boxs) > 0:
                            for box in boxs:
                                lattice["children"].append({"text": box.code, "id": box.id})
                            cabinet["children"].append(lattice)
                        else:
                            cabinet["children"].append(lattice)
                tree_data.append(cabinet)
            result['tree'] = json.dumps(tree_data)
            records = records.order_by("-storage_time")
            result['data'] = records
        except Exception as e:
            print traceback.format_exc()
            return err_requests("500")
        return render(request, "archives_file/outPut.html", result)
    else:
        return err_requests("500")


def file_add(request):
    if request.method.upper() == "POST":  # 添加
        try:
            serial = request.POST.get('serial')
            title = request.POST.get('title')
            storage_type = request.POST.get('storage_type')
            storage_deadline = request.POST.get('storage_deadline')
            secret_level = request.POST.get('secret_level')
            cabinet_id = request.POST.get('cabinet_id')
            lattice_id = request.POST.get('lattice_id')
            box_id = request.POST.get('box_id')
            cabinet = Cabinet.objects.get(id=int(cabinet_id))
            lattice = Lattice.objects.get(id=int(lattice_id))
            box = Box.objects.get(id=int(box_id))
            owner_id = request.POST.get('owner_id')
            owner = CloudAuthUser.objects.get(id=int(owner_id))
            storage_method = request.POST.get('storage_method')
            operator_id = request.POST.get('operator_id')
            operator = CloudAuthUser.objects.get(id=int(operator_id))
            photo = request.POST.get('photo')  # TODO 上传图片待做
            if not photo:  # 没有上传图片，默认值为五个逗号
                photo = ",,,,,"
            # 状态
            file_status = '在库'
            # 借出记录默认为-1
            borrowing_record_id = -1
            borrowing_record = BorrowRecord(id=int(borrowing_record_id))
            file = ArchivesFile(serial=serial, title=title, storage_type=storage_type,
                                storage_deadline=storage_deadline, secret_level=secret_level, cabinet=cabinet,
                                lattice=lattice, box=box, photo=photo, owner=owner, storage_method=storage_method,
                                operator=operator, file_status=file_status, borrowing_record=borrowing_record)
            file.save()
            return success_requests()
        except Exception as e:
            print traceback.format_exc()
            return err_requests("500")
    else:
        print "this request method not allowed : %s" % request.method
        return err_requests("500")


def file_update(request):
    if request.method.upper() == "POST":  # 修改
        params = get_body(request)
        serial = params.get("serial")
        title = params.get("title")
        storage_type = params.get("storage_type")
        storage_deadline = params.get("storage_deadline")
        secret_level = params.get("secret_level")
        cabinet_id = params.get("cabinet_id")
        lattice_id = params.get("lattice_id")
        box_id = params.get("box_id")
        storage_method = params.get("storage_method")
        operator_id = params.get("operator_id")
        owner_id = params.get("owner_id")
        photo = params.get("photo")
        # TODO 图片暂不更新
        borrowing_record_id = params.get("borrowing_record_id")
        if not serial:
            print "params not correct, serial :%s ." % serial
            return err_requests("500")
        try:
            archives_file = ArchivesFile.objects.get(serial=serial)
            if title:
                archives_file.title = title
            if storage_type:
                archives_file.storage_type = storage_type
            if storage_deadline:
                archives_file.storage_deadline = storage_deadline
            if secret_level:
                archives_file.secret_level = secret_level
            if cabinet_id:
                cabinet = Cabinet.objects.get(id=int(cabinet_id))
                archives_file.cabinet = cabinet
            if lattice_id:
                lattice = Lattice.objects.get(id=int(lattice_id))
                archives_file.lattice = lattice
            if box_id:
                box = Box.objects.get(id=int(box_id))
                archives_file.box = box
            if storage_method:
                archives_file.storage_method = storage_method
            if operator_id:
                operator = CloudAuthUser.objects.get(id=int(operator_id))
                archives_file.operator = operator
            if owner_id:
                owner = CloudAuthUser.objects.get(id=int(owner_id))
                archives_file.owner = owner
            if photo:
                archives_file.photo = photo
            if borrowing_record_id and int(borrowing_record_id) < 0:
                archives_file.file_status = '在库'
                archives_file.borrowing_record = BorrowRecord(id=int(borrowing_record_id))
            elif borrowing_record_id and int(borrowing_record_id) > 0:
                archives_file.file_status = "借出"
                archives_file.borrowing_record = BorrowRecord(id=int(borrowing_record_id))
            archives_file.save()
            return success_requests()
        except Exception as e:
            print traceback.format_exc()
            return err_requests("500")
    else:
        print "this request method not allowed : %s" % request.method
        return err_requests("500")


def file_del(request):
    if request.method.upper() == "POST":  # 删除
        params = get_body(request)
        json_serials = params.get("serials")
        if not json_serials:
            print "params not correct, serials %s ." % json_serials
            return err_requests("500")
        try:
            str_serials = ','.join(json_serials)
            ArchivesFile.objects.extra(where=['serial in (' + str_serials + ')']).delete()
            return success_requests()
        except Exception as e:
            print traceback.format_exc()
            return err_requests("500")
    else:
        print "this request method not allowed : %s" % request.method
        return err_requests("500")
